<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="800px" :title="`${drawerProps.title}菜单`">
    <!-- 警告提示 -->
    <el-alert title="新增菜单，需要在角色管理内配置权限才可使用" type="warning" show-icon :closable="false" class="mb-6" />
    <el-form
      ref="ruleFormRef"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
      label-position="top"
    >
      <el-row :gutter="20">
        <el-col :span="14">
          <el-form-item label="文件路径" prop="component">
            <el-input v-model="drawerProps.row!.component" placeholder="如：view/...*/...*/index" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="展示名称" prop="title">
            <el-input v-model="drawerProps.row!.meta.title" clearable />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="路由Name" prop="name">
            <el-input v-model="drawerProps.row!.name" placeholder="请输入路由 name" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="路由Path" prop="path">
            <el-input v-model="drawerProps.row!.path" placeholder="如：/home/*" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否隐藏" prop="isHide">
            <el-select v-model="drawerProps.row!.meta.isHide" clearable>
              <el-option v-for="item in isHide" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="父节点 ID" prop="id">
            <el-select v-model="drawerProps.row!.id" placeholder="根目录" disabled>
              <el-option :label="drawerProps.row!.meta.title" :value="drawerProps.row!.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="图标" prop="icon">
            <el-select v-model="drawerProps.row!.meta.icon" clearable>
              <el-option v-for="item in iconList" :key="item.value" :label="item.label" :value="item.value">
                {{ item.label }}
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="高亮菜单" prop="activeMenu">
            <el-input v-model="drawerProps.row!.activeMenu" placeholder="routerHolder" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="是否外链 ID" prop="isLink">
            <el-select v-model="drawerProps.row!.meta.isLink">
              <el-option :label="'是'" :value="true" />
              <el-option :label="'否'" :value="false" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否全屏" prop="isFull">
            <el-select v-model="drawerProps.row!.meta.isFull" clearable>
              <el-option :label="'是'" :value="true" />
              <el-option :label="'否'" :value="false" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否固定标签" prop="isAffix">
            <el-select v-model="drawerProps.row!.meta.isAffix" clearable>
              <el-option v-for="item in isHide" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="重定向" prop="redirect">
            <el-select v-model="redirectEnabled" placeholder="请选择">
              <el-option :label="'是'" :value="true" />
              <el-option :label="'否'" :value="false" />
            </el-select>
          </el-form-item>
          <el-form-item label="重定向路径" v-if="redirectEnabled">
            <el-input v-model="drawerProps.row!.redirect" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="KeepAlive" prop="isKeepAlive">
            <el-select v-model="drawerProps.row!.meta.isKeepAlive" clearable>
              <el-option :label="'是'" :value="true" />
              <el-option :label="'否'" :value="false" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import * as Icons from "@element-plus/icons-vue";
import { ref, reactive, computed } from "vue";
import { ElMessage, FormInstance } from "element-plus";

const rules = reactive({});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Menu.MenuOptions>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});
// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  console.log("父组件传来的参数:", params); // 这里打印
  drawerProps.value = params;
  drawerVisible.value = true;
  const isAdd = params.title === "新增";
  const hasParent = !!params.row?.id;

  if (isAdd && hasParent) {
    // 保留父节点 ID 和 meta.title，其它字段清空
    drawerProps.value.row = {
      // id: params.row.id,
      id: "",
      meta: {
        title: "",
        isHide: false,
        isLink: false,
        isFull: false,
        isAffix: false,
        isKeepAlive: true,
        icon: ""
      },
      component: "",
      name: "",
      path: "",
      redirect: "",
      activeMenu: "",
      parentId: params.row.id
    };
  } else if (!params.row?.id) {
    // 初始化为空数据（新增根节点）
    drawerProps.value.row = {
      component: "",
      name: "",
      path: "",
      redirect: "",
      activeMenu: "",
      meta: {
        isHide: false,
        isLink: false,
        isFull: false,
        isAffix: false,
        isKeepAlive: true,
        icon: "",
        title: ""
      }
    };
  }
};
// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    // 把 Tile 的值赋给 meta.title
    if (!drawerProps.value.row.meta) {
      drawerProps.value.row.meta = {};
    }
    // drawerProps.value.row.meta.title = Tile.value;
    const dataToSend = { ...drawerProps.value.row };
    console.log("提交的数据：", dataToSend);
    try {
      // await update(dataToSend);
      await drawerProps.value.api?.(dataToSend);
      // ElMessage.success({ message: `修改用户成功！` });
      ElMessage.success({ message: `添加${drawerProps.value.title}菜单成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};
const redirectEnabled = computed({
  get() {
    return drawerProps.value.row?.redirect != null;
  },
  set(val: boolean) {
    if (!val) {
      drawerProps.value.row!.redirect = null;
    } else if (!drawerProps.value.row!.redirect) {
      drawerProps.value.row!.redirect = "";
    }
  }
});

defineExpose({
  acceptParams
});

const isHide = ref([
  { label: "是", value: true },
  { label: "否", value: false }
]);

const iconList = ref(
  Object.keys(Icons).map(key => ({
    label: key,
    value: key
  }))
);
</script>
